package org.wmine.core;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringBufferInputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

public class IndexParserGenerator{	
	IProjectManager pm =ProjectManager.getUniqueInstance();
	private DocumentBuilder parser;
	
	
	String []elements;
	
	public IndexParserGenerator(){
		elements=new String[4];
		elements[0]="Name";
		elements[1]="Type";
		elements[2]="Sub-Type";
		elements[3]="Description";
	}
	/*returns parsed index file 
	 * 
	 */	 
	
	
	
	Document parseIndex(){		 
		Document xmlDocument = null;
		String read_data=null;
		try{
			read_data=pm.readFile("Index.xml");
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			parser = factory.newDocumentBuilder();
			//System.out.println(read_data);
			
			@SuppressWarnings("deprecation") 
			//			xmlDocument = parser.parse(read_data);
			StringBufferInputStream stringStream = new StringBufferInputStream(read_data);
			xmlDocument = parser.parse(stringStream);
		}
		catch(FileNotFoundException e)
		{	e.printStackTrace();
		
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return xmlDocument;
	}
	/*This method adds file data to index
	 */
	@SuppressWarnings("deprecation")
	public boolean addFile(String []val) {	 
		if(pm.isProjectOpened()){	
			Document xmldoc=parseIndex();
			Element root = xmldoc.getDocumentElement();
			Element e1 = xmldoc.createElementNS(null, "File");
			Element e2 ;
			Text n;
			for(int i=0;i<val.length;i++){
				e2= xmldoc.createElementNS(null, elements[i]);
				n = xmldoc.createTextNode(val[i]);
				
				e2.appendChild(n);
				e1.appendChild(e2);
			}
			root.appendChild(e1);
			//System.out.println(getXMLString());
			pm.writeFile("Index.xml",getXMLString(xmldoc));
			return true;
		}//if
		return false;
	}
	
	
	public String getXMLString(Document xmldoc) {
		
		StringWriter stringWriter = new StringWriter();
		
		DOMSource domSource = new DOMSource(xmldoc);
		StreamResult streamResult = new StreamResult(stringWriter);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = null;
		try {
			serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.INDENT,"yes");
			serializer.transform(domSource, streamResult);
			
		} 
		catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} 
		catch (TransformerException e) {
			e.printStackTrace();
		}
		return stringWriter.toString();//It prints all XML in String format 
	}
	/*this method list files in the index file
	 */
	String[] getIndexFiles(String type){	
		String list_of_files[] = null;
		Document xmldoc=parseIndex();
		NodeList paramList=xmldoc.getElementsByTagName("File");
		int count=0;
		if(paramList!=null && type==null){		
			for(int i=0;i<paramList.getLength();i++){
				Element ele=(Element)paramList.item(i);
				count++;
			}
			if(count!=0)
				list_of_files=new String[count];
			int j=0;
			for(int i=0;i<paramList.getLength();i++){
				Element ele=(Element)paramList.item(i);
				list_of_files[j]=returnValue(ele,"Name");
				j++;
			}
		}
		else if(paramList!=null){		
			for(int i=0;i<paramList.getLength();i++){
				Element ele=(Element)paramList.item(i);
				if(type.equals(returnValue(ele,"Type"))){	
					count++;
					
				}
			}
			if(count!=0)
				list_of_files=new String[count+1];
			int j=0;
//			System.out.println("paramlist length in Indexparser"+count);
			for(int i=0;i<paramList.getLength();i++){
				Element ele=(Element)paramList.item(i);
				if(type.equals(returnValue(ele,"Type"))){
			//		System.out.println("Adding at the index : "+j);
							
					list_of_files[j]=returnValue(ele,"Name");
					
					j++;
				}
				else 
					continue;
			}
		}
		
		return list_of_files;
	}

	String[] getIndexSubtypes(String type)
	{	String sub_TypeList[];
		Document xmldoc=parseIndex();
		NodeList paramList=xmldoc.getElementsByTagName("File");
		sub_TypeList=new String[paramList.getLength()*2+1];
		int j=0;
		if(paramList!=null)
		{	
				for(int i=0;i<paramList.getLength();i++)
				{	Element ele=(Element)paramList.item(i);
					if(type.equals(returnValue(ele,"Type")))
					{	sub_TypeList[j++]=returnValue(ele,"Name");
						sub_TypeList[j]=returnValue(ele,"Sub-Type");
						System.out.println("in Index Parser Generator : list of files in index  "+sub_TypeList[j]);
						j++;
					}
				}
		}
		
		return sub_TypeList;
	}

	/*returns value of element
	 * 
	 */
	String returnValue(Element element,String fetch){
		NodeList paramList=element.getElementsByTagName(fetch);			
		Element desiredElement=(Element)paramList.item(0);
		Text paramText=(Text)desiredElement.getFirstChild();
		String resultString = " ";
		resultString = paramText.getNodeValue();
	//	System.out.println("in return value"+resultString);
		return(resultString);
	}
}